import React from "react";
import styles from './index.less';
import { Modal, DatePicker, InputItem, Picker, Toast } from 'antd-mobile';
import ReactDOM from 'react-dom';
import SeModal from '@/components/searchEmployee';
import { getMastId } from '@/utils/tools';
import UserServices from '@/services/user';
import { requestSuccess, addHidden, removeHidden } from '@/utils/tools';
// 添加预支单，请求后返回值
class aiModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      companyCode: props.companyCode,
      visible: true,
      message: props.message,
      content: props.content,
      success: props.success,
      cancel: props.cancel,
      datepickerActiveKey: '',
      datepickerVisible: false,
      values: {
        payee: '',
        chargeEmployees: '',
        adBeginDate: '',
        adEndDate: '',
        claimAmt: '',
        currency: '',
        exchangeRateDate: '',
        accountHolder: '',
        bankAccount: '',
        bankName: '',
        remark: ''
      }
    };
    window.cordovaBackEvents.push(() => {
      this.handleCancel();
    });
  }

  handleShowDatePicker = (activeKey) => {
    this.setState({
      datepickerActiveKey: activeKey,
      datepickerVisible: true
    })
  }

  handleFormatData = (data) => {
    const id = getMastId();

    return {
      ...id,
      advMast:{
        ...data
      }
    }
  }

  handleSuccess = (e) => {
    const data = this.handleFormatData(this.state.values);
    console.log(data);
    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.saveAdvanceInfo(data).then(res => {
      console.log(res);
      if(requestSuccess(res)){
        this.setState({
          visible: false,
        });
        // res.data.advanceInfo 数组
        this.state.success && this.state.success(res.data.advanceInfo);
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)
    // this.setState({
    //   visible: false,
    // });
    // this.state.success && this.state.success({...this.state.values});
  }

  handleCancel = (e) => {
    removeHidden();
    this.setState({
      visible: false,
    });
    removeHidden();
    this.state.cancel && this.state.cancel();
  }

  handleSaveDatepickerValue = (date) => {
    if(this.state.datepickerActiveKey){
      this.onChange(global.moment(date).format('YYYY-MM-DD').valueOf(), this.state.datepickerActiveKey);
      this.setState({
        datepickerVisible: false
      })
    }
  }

  onChange = (value, key) => {
    this.setState({
      values: {
        ...this.state.values,
        [key]: value
      }
    })
  }

  handleSelectedEmployee = (key)=>{
    SeModal.open({
      success: (result) => {
        setTimeout( () => {
          this.setState({values: {
            ...this.state.values,
            [key]: result.employees
          }});
          this.getData();
        }, 0);
      },
      cancel: () => {

      }
    })
  }

  handleListLabel = (list) => {
    return global._.map(list, item => {
      return {
        label: item,
        value: item
      }
    });
  }

  getData = () => {
    const id = getMastId();

    // 获取 银行信息 与 币种的labels
    UserServices.getAddAdvanceInfoLabel({
      ...id,
      advMast:{
        payee: this.state.values.payee
      }
    }).then(res => {
      if(requestSuccess(res)){
        const currencyList = 'XMC' == this.state.companyCode || '1100'== this.state.companyCode
        ?
        res.data.currencyListX
        :
        res.data.currencyListY;

        this.setState({
          currencyList: currencyList,
          values: {
            ...this.state.values,
            ...res.data.advMast
          }
        })
      }
    })
  }

  componentDidMount(){
    this.getData();
    addHidden();
  }

  render() {
    return (
      <Modal
        visible={this.state.visible}
        className={styles.aiModal}
      >
      <div className={styles.modalWrapper}>
        <DatePicker
          visible={this.state.datepickerVisible}
          mode='date'
          value={this.state.datepickerValue}
          onOk={this.handleSaveDatepickerValue}
          onDismiss={() => this.setState({ datepickerVisible: false })}
        />
        <div className={styles.info}>Advance Info</div>
        <div className={styles.results}>
          <div className={styles.list}>
            <div className={styles.header}>Advance Info Setting</div>
            <div className={styles.item} onClick={() => this.handleSelectedEmployee('payee')}>
              <div className={styles.des}>*Payee</div>
              <div className={styles.value}>{this.state.values.payee || 'Select'}</div>
            </div>
            <div className={styles.item} onClick={() => this.handleSelectedEmployee('chargeEmployees')}>
              <div className={styles.des}>*Charge Employee</div>
              <div className={styles.value}>{this.state.values.chargeEmployees || 'Select'}</div>
            </div>
            <div className={styles.item} onClick={() => this.handleShowDatePicker('adBeginDate')}>
              <div className={styles.des}>*Advance Date From</div>
              <div className={styles.value}>{ this.state.values.adBeginDate || 'Select'}</div>
            </div>
            <div className={styles.item} onClick={() => this.handleShowDatePicker('adEndDate')}>
              <div className={styles.des}>*Advance Date To</div>
              <div className={styles.value}>{ this.state.values.adEndDate || 'Select'}</div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>*Amount</div>
              <div className={styles.value}>
                <InputItem
                  clear
                  placeholder="click input"
                  value={this.state.values.claimAmt}
                  onChange={(value) => this.onChange(value, 'claimAmt')}
                  ></InputItem>
              </div>
            </div>
            <Picker data={this.handleListLabel(this.state.currencyList)} cols={1} onChange={(values) => this.onChange(values[0], 'currency')}>
              <div className={styles.item}>
                <div className={styles.des}>*Currency（币种）</div>
                <div className={styles.value}>{this.state.values.currency || 'Select'}</div>
              </div>
            </Picker>
            <div className={styles.item} onClick={() => this.handleShowDatePicker('exchangeRateDate')}>
              <div className={styles.des}>*Exchange Rate Date</div>
              <div className={styles.value}>{this.state.values.exchangeRateDate || 'Select'}</div>
            </div>
          </div>
          <div className={styles.list}>
            <div className={styles.header}>Bank Info</div>
            <div className={styles.item}>
              <div className={styles.des}>*Account Holder</div>
              <div className={styles.value}>
                <InputItem
                  clear
                  placeholder="click input"
                  value={this.state.values.accountHolder}
                  onChange={(value) => this.onChange(value, 'accountHolder')}
                  ></InputItem>
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>*Bank Account</div>
              <div className={styles.value}>
                <InputItem
                  clear
                  placeholder="click input"
                  value={this.state.values.bankAccount}
                  onChange={(value) => this.onChange(value, 'bankAccount')}
                  ></InputItem>
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>*Bank Name</div>
              <div className={styles.value}>
                <InputItem
                  clear
                  placeholder="click input"
                  value={this.state.values.bankName}
                  onChange={(value) => this.onChange(value, 'bankName')}
                  ></InputItem>
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>*Remark</div>
              <div className={styles.value}>
                <InputItem
                  clear
                  placeholder="click input"
                  value={this.state.values.remark}
                  onChange={(value) => this.onChange(value, 'remark')}
                  ></InputItem>
              </div>
            </div>
          </div>
        </div>
        <div className={styles.footerBtns}>
          <div onClick={this.handleSuccess}>Save</div>
          <div onClick={this.handleCancel}>Cancel</div>
        </div>
      </div>
      </Modal>
    );
  }
}

export default {
  open(params){
    let div = document.createElement('div');
    document.body.appendChild(div);
    ReactDOM.render(React.createElement(aiModal, params), div);
  }
};
